package com.minelx.datamicroscope.querylanguage.data;

import com.alibaba.fastjson.JSONObject;

import java.util.List;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

public class CollectingGroup {

	private final String resourceName;

	private final CollectingKey collectingKey;

	private final List<CollectingField> collectingFields;

	private CollectingGroup(String resourceName, CollectingKey collectingKey, List<CollectingField> collectingFields) {
		this.resourceName = resourceName;
		this.collectingKey = collectingKey;
		this.collectingFields = collectingFields;
	}

	public JSONObject render() {
		JSONObject result = new JSONObject();
		result.put("resourceName", resourceName);
		result.put("join", collectingKey.getJoin());
		result.put("on", collectingKey.getOn());
		result.put("collecting", collectingFields.stream()
				.collect(toMap(CollectingField::getAlias, CollectingField::getField)));
		// add conditions specifications if needed
		if (!collectingKey.getConditions().isEmpty()) {
			result.put("conditions", collectingKey.getConditions().stream().map(Condition::toJSON).collect(toList()));
		}
		return result;
	}

	public static CollectingGroup create(String resourceName, CollectingKey collectingKey, List<CollectingField> collectingFields) {
		return new CollectingGroup(resourceName, collectingKey, collectingFields);
	}

	public CollectingKey getCollectingKey() {
		return collectingKey;
	}

	public String getResourceName() {
		return resourceName;
	}
}
